<?php
/**
 * rabbit核心框架
 */
class Core
{
    // 运行程序
    public function run()
    {
        spl_autoload_register(array($this, 'loadClass'));

//        $this->setReporting();
//
//        $this->removeMagicQuotes();
//
//        $this->unregisterGlobals();

        $this->Route();
    }
    // 路由处理
    private function Route()
    {
        //获取参数信息
        $string = $_SERVER['REQUEST_URI'];
        $string = str_replace('/index.php',  '', $string);
        $arr = explode('/', $string);
        $data = [];
        //控制器
        $controller = isset($arr[1]) && $arr[1] ? $arr[1] : CONTROLLER_DEFUALT;
        $old_controller = $controller;
        $controller .= 'Controller';
        //方法
        $active = isset($arr[2]) && $arr[2] ? $arr[2] : ACTIVE_DEFUALT;

        //根据请求方式分发到相应的控制器，
        if($_SERVER['REQUEST_METHOD'] == 'GET') {
            $str = $_SERVER['PATH_INFO'];
            $new = '';
            //路由选择  把匹配的数据对应的相应的变量下
//            $route = [
//                'index/index/(\d+)/(\d+).html'=>['id', 'ids'],
//                'index/index/(\d+)/(\d+)/(\d+).html'=>['id', 'ids', 'cate_id'],
//                'article/list/(\d+).html'=>['id'],
//            ];

            $route = require APP_PATH . 'config/route.php';
            if(is_array($route) && count($route)>0){
                foreach ($route as $key => $value) {
                    $key = str_replace('/', '\/', $key);
                    $s= preg_match('/'.$key.'/', $str, $daa);
                    if(isset($daa[0]) && $daa[0]){
                        unset($daa[0]);
                        $new = array_combine($value[0], $daa);
                        break;
                    }
                }
            }
            $data = $new;

        }elseif($_SERVER['REQUEST_METHOD'] == 'POST') {
            $data = $_POST;
        }

        $app = new $controller($old_controller, $active);
        call_user_func(array($app,$active),$data);

//        $controllerName = 'Index';
//        $action = 'index';
//        if (!empty($_GET['url'])) {
//            $url = $_GET['url'];
//            $urlArray = explode('/', $url);
//            // 获取控制器名
//            $controllerName = ucfirst($urlArray[0]);
//            // 获取动作名
//            array_shift($urlArray);
//            $action = empty($urlArray[0]) ? 'index' : $urlArray[0];
//            //获取URL参数
//            array_shift($urlArray);
//            $queryString = empty($urlArray) ? array() : $urlArray;
//        }
//        // 数据为空的处理
//        $queryString  = empty($queryString) ? array() : $queryString;
//        // 实例化控制器
//        $controller = $controllerName . 'Controller';
//        $dispatch = new $controller($controllerName, $action);
//        // 如果控制器存和动作存在，这调用并传入URL参数
//        if ((int)method_exists($controller, $action)) {
//            call_user_func_array(array($dispatch, $action), $queryString);
//        } else {
//            exit($controller . "控制器不存在");
//        }
    }
    // 检测开发环境
    private function setReporting()
    {
        if (APP_DEBUG === true) {
            error_reporting(E_ALL);
            ini_set('display_errors','On');
        } else {
            error_reporting(E_ALL);
            ini_set('display_errors','Off');
            ini_set('log_errors', 'On');
            ini_set('error_log', RUNTIME_PATH. 'logs/error.log');
        }
    }
    // 删除敏感字符
    private function stripSlashesDeep($value)
    {
        $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
        return $value;
    }
    // 检测敏感字符并删除
    private function removeMagicQuotes()
    {
        if ( get_magic_quotes_gpc()) {
            $_GET = stripSlashesDeep($_GET );
            $_POST = stripSlashesDeep($_POST );
            $_COOKIE = stripSlashesDeep($_COOKIE);
            $_SESSION = stripSlashesDeep($_SESSION);
        }
    }
    // 检测自定义全局变量（register globals）并移除
    private function unregisterGlobals()
    {
        if (ini_get('register_globals')) {
            $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
            foreach ($array as $value) {
                foreach ($GLOBALS[$value] as $key => $var) {
                    if ($var === $GLOBALS[$key]) {
                        unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }
    // 自动加载控制器和模型类
    private static function loadClass($class)
    {
        $class = ucfirst($class);
        $frameworks = FRAME_PATH . $class . '.class.php';
        $controllers = APP_PATH . 'app/controller/' . $class . '.class.php';
        $models = APP_PATH . 'app/model/' . $class . '.class.php';
        include_once APP_PATH.'system/controller/Controller.class.php';
        include_once APP_PATH.'system/controller/View.class.php';
        include_once APP_PATH.'system/models/Model.class.php';
        include_once APP_PATH.'system/models/Sql.class.php';
        include_once APP_PATH.'system/controller/Session.class.php';
        include_once APP_PATH.'system/controller/Cookie.class.php';
        if (file_exists($frameworks)) {
            // 加载框架核心类
            include $frameworks;
        } elseif (file_exists($controllers)) {
            // 加载应用控制器类
            include $controllers;
        } elseif (file_exists($models)) {
            //加载应用模型类
            include $models;
        } else {
            /* 错误代码 */
        }
    }
}
